﻿using CommunityToolkit.Maui.Core.Primitives;
using CommunityToolkit.Maui.Views;
using MauiApp1.DeviceServices;
using MauiApp1.Models;
using Microsoft.Maui.Controls.PlatformConfiguration;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;


namespace MauiApp1.ViewModels
{
    public class VideoInfoPageViewModel : BindableObject, IQueryAttributable
    {
        private string _title;

        public string Title
        {
            get { return _title; }
            set { _title = value; OnPropertyChanged(nameof(Title)); }
        }

        private int _VideoId;
        public int VideoId
        {
            get { return _VideoId; }
            set { _VideoId=value; OnPropertyChanged(nameof(VideoId)); }
        }

        private VideoInfo _Info;
        public VideoInfo Info
        {
            get { return _Info; }
            set { _Info = value; OnPropertyChanged(nameof(Info));}
        }


        private ObservableCollection<VideoUrl> _VideoUrls;
        public ObservableCollection<VideoUrl> VideoUrls
        {
            get { return _VideoUrls; }
            set { _VideoUrls = value; OnPropertyChanged(nameof(VideoUrls)); }
        }


        private string _CurrentUrl;

        public string CurrentUrl
        {
            get { return _CurrentUrl; }
            set { _CurrentUrl = value; OnPropertyChanged(nameof(CurrentUrl)); }
        }


        private ICommand _ClickCommand;
        public ICommand ClickCommand => _ClickCommand ??= new Command(GetUrl);


        private Timer _Timer;

        public DeviceOrientationService orientationService;

        public double FullHeight = 0;

        public VideoInfoPageViewModel()
        {
            var d = DeviceDisplay.Current.MainDisplayInfo;
            FullHeight = 423.5;
            VideoHeight = 250;
            orientationService =new DeviceOrientationService();
            ShowOther = true;
            PlayText = "播放";
            FullText = "全屏";
            VideoUrls =new ObservableCollection<VideoUrl>();
            _Timer=new Timer(new TimerCallback(timerCall),null,TimeSpan.Zero,TimeSpan.FromSeconds(1));
            
        }

        void IQueryAttributable.ApplyQueryAttributes(IDictionary<string, object> query)
        {
           if(query.ContainsKey("VideoId"))
            {
                VideoId =Convert.ToInt32(query["VideoId"]);
                 GetVideoInfo();
            }
        }

        public async void GetVideoInfo()
        {
            var res = await APIService.GetVideoInfo(VideoId);
            if(res!=null && res.list != null && res.list.Any()) 
            {
                CurrentUrl = "";
                VideoUrls.Clear();
                Info = res.list.FirstOrDefault();
                Title = Info.vod_name;
                if (!string.IsNullOrEmpty(Info.vod_play_url))
                {
                    var arr=Info.vod_play_url.Replace("$$$", "*").Split('*');
                    foreach(var item in arr)
                    {
                        var arr2 = item.Split('$');
                        VideoUrls.Add(new VideoUrl() { title = arr2[0], url = arr2[1] });
                    }

                    CurrentUrl = VideoUrls.FirstOrDefault().url;

                    foreach(var item in VideoUrls) { item.select = false; }
                    VideoUrls.FirstOrDefault().select = true;
                }
            }
        }

        public void GetUrl(object obj)
        {
            var url = obj as VideoUrl; if(url!=null)
            {
                foreach (var item in VideoUrls) { item.select = false; }
                CurrentUrl =url.url;
                url.select = true;
            }
        }


        private string _PlayText;

        public string PlayText
        {
            get { return _PlayText; }
            set { _PlayText = value; OnPropertyChanged(nameof(PlayText)); }
        }


        private ICommand _PlayCommand;
        public ICommand PlayCommand => _PlayCommand ??= new Command(Play);

        public void Play(object obj)
        {
            var mediaElement = obj as MediaElement;

            if (mediaElement.CurrentState == MediaElementState.Stopped ||
            mediaElement.CurrentState == MediaElementState.Paused)
            {
                mediaElement.Play();
                PlayText = "暂停";
            }
            else if (mediaElement.CurrentState == MediaElementState.Playing)
            {
                mediaElement.Pause();
                PlayText = "播放";
            }
        }

        public MediaElement media { get; set; }



        private string _DurionText;

        public string DurionText
        {
            get { return _DurionText; }
            set { _DurionText = value; OnPropertyChanged(nameof(DurionText)); }
        }


        private string _PositionText;

        public string PositionText
        {
            get { return _PositionText; }
            set { _PositionText = value; OnPropertyChanged(nameof(PositionText)); }
        }

        public void timerCall(object obj)
        {
            if (media != null)
            {
                DurionText = $"{media.Duration.Hours.ToString().PadLeft(2,'0')}:{media.Duration.Minutes.ToString().PadLeft(2, '0')}:{media.Duration.Seconds.ToString().PadLeft(2, '0')}";
                PositionText = $"{media.Position.Hours.ToString().PadLeft(2, '0')}:{media.Position.Minutes.ToString().PadLeft(2, '0')}:{media.Position.Seconds.ToString().PadLeft(2, '0')}";
                if (media.CurrentState != MediaElementState.Playing)
                {
                    PlayText = "播放";
                   
                }
                else
                {
                    PlayText = "暂停";
                }

                if (media.CurrentState == MediaElementState.Buffering)
                {
                    IsLoading = true;
                }
                else
                {
                    IsLoading = false;
                }

                MaxSeconds = media.Duration.TotalSeconds;
                CurrentPos = media.Position.TotalSeconds;
            }
        }


        private double _MaxSeconds;

        public double MaxSeconds
        {
            get { return _MaxSeconds; }
            set { _MaxSeconds = value; OnPropertyChanged(nameof(MaxSeconds)); }
        }


        private double _CurrentPos;

        public double CurrentPos
        {
            get { return _CurrentPos; }
            set { _CurrentPos = value; OnPropertyChanged(nameof(CurrentPos)); }
        }


        private bool _FullScreen;

        public bool FullScreen
        {
            get { return _FullScreen; }
            set { _FullScreen = value; OnPropertyChanged(nameof(FullScreen)); }
        }


        private double _VideoHeight;

        public double VideoHeight
        {
            get { return _VideoHeight; }
            set { _VideoHeight = value; OnPropertyChanged(nameof(VideoHeight)); }
        }


        private string _FullText;

        public string FullText
        {
            get { return _FullText; }
            set { _FullText = value; OnPropertyChanged(nameof(FullText)); }
        }

        private ICommand _FullCommand;
        public ICommand FullCommand => _FullCommand ??= new Command(Full);

        public void Full()
        {
            if(media!=null)
            {
                
                FullScreen = !FullScreen;
                if (FullScreen)
                {

                    orientationService.SetDeviceOrientation(DisplayOrientation.Landscape);
                    orientationService.SetNavBar(false);
                    VideoHeight = FullHeight;
                    ShowOther = false;
                    ShowControl = false;
                    FullText = "返回";



                }
                else
                {
                    orientationService.SetDeviceOrientation(DisplayOrientation.Portrait);
                    orientationService.SetNavBar(true);
                    VideoHeight = 250;
                    ShowOther = true;
                    ShowControl = false;
                    FullText = "全屏";
                }
            }
        }


        private bool _ShowControl;

        public bool ShowControl
        {
            get { return _ShowControl; }
            set { _ShowControl = value; OnPropertyChanged(nameof(ShowControl)); }
        }

        private ICommand _GridCommand;
        public ICommand GridCommand => _GridCommand ??= new Command(Show);

        public void Show()
        {
            ShowControl = !ShowControl;
        }


        private bool _ShowOther;

        public bool ShowOther
        {
            get { return _ShowOther; }
            set { _ShowOther = value; OnPropertyChanged(nameof(ShowOther)); }
        }


        private bool _IsLoading;
        public bool IsLoading
        {
            get { return _IsLoading; }
            set { _IsLoading = value; OnPropertyChanged(nameof(IsLoading)); }
        }

        private ICommand _NextCommand;
        public ICommand NextCommand => _NextCommand ??= new Command(NexiUrl);

        public void NexiUrl(object obj)
        {
            if (VideoUrls.Any() && !IsLoading)
            {
                IsLoading = true;
                var m = VideoUrls.FirstOrDefault(o => o.url == CurrentUrl);
                if (m != null)
                {
                    var index = VideoUrls.IndexOf(m);
                    index++;
                    if (index < VideoUrls.Count)
                    {
                        foreach (var item in VideoUrls) { item.select = false; }
                        CurrentUrl = VideoUrls[index].url;
                        VideoUrls[index].select = true;
                    }
                }
            }
            IsLoading = false;
        }

    }
}
